#include <FL/Fl.H>
#include <FL/Fl_Gl_Window.H>
#include <FL/gl.h>
#include <math.h>
#include <vector> 
#include <cassert>
#include <fstream>
 
void write_mat(const char* fpath, std::vector<  float  > y) { 
  std::ofstream fout(fpath, std::ios::out | std::ios::binary);
  assert(fout);
  int len = y.size();
 
  fout.write( (char*)&len, sizeof(int));
  fout.write( (char*)&y[0], sizeof(float)*len);
  fout.close();
}


class myGL : public Fl_Gl_Window { 
  std::vector<float> click_x;
  std::vector<float> click_y;

  void draw() {
    if (!valid()) {
      valid(1);
      glMatrixMode (GL_PROJECTION);
      glLoadIdentity ();
      glOrtho (0, w(), h(), 0, 0, 1);
      glMatrixMode (GL_MODELVIEW);
      glDisable(GL_DEPTH_TEST);
    }
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE);
    glVertex2f(0, h()/2);
    glVertex2f(w(), h()/2);
    glEnd();

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_STRIP);
    for ( unsigned i=0; i<click_x.size(); i++ ) {
      glVertex2f(click_x[i], click_y[i]);
      printf("drawing vertex = (%f, %f)\n", click_x[i], click_y[i]);
    }
    glEnd();
  }
  
  int handle( int event ) {
    switch ( event ) {
    case FL_PUSH:
      if( Fl::event_button() == 1 ) {
	printf("Left mouse button pressed.\n");
	printf("width: %d", x());
	click_x.push_back( (float)Fl::event_x () );
	click_y.push_back( (float)Fl::event_y () );
	redraw();
	return 0;
      }
    default:
      // letting the base class handle events I don't care
      // about, or don't dare mess with.
      return Fl_Gl_Window::handle(event);
    }
  }

public:
  myGL(int X,int Y,int W,int H,const char*L=0) : Fl_Gl_Window(X,Y,W,H,L) {
    end();
  }
};



int main(void) {
  // this creates our window
  Fl_Window win(500, 500);
  myGL gWin(10, 10, win.w()-20, win.h()-20);
  //not sure how/why this works
  win.resizable(&gWin);
  //makes the window show up
  win.show();
  // This causes the fltk stuff to run until the window's closed
  return(Fl::run());
}
